/**
 * Created by Tuffy on 16/6/6.
 */
'use strict';

(function() {
    Date.prototype.YYYY_MM_DD = 'yyyy-MM-dd';
    Date.prototype.YYYY_MM_DD_HH_MM_SS = 'yyyy-MM-dd hh:mm:ss';

    Date.prototype.format = function(formatStr){
        var str = formatStr;
        var Week = ['日','一','二','三','四','五','六'];

        str=str.replace(/yyyy|YYYY/,this.getFullYear());
        str=str.replace(/yy|YY/,(this.getYear() % 100)>9?(this.getYear() % 100).toString():'0' + (this.getYear() % 100));
        // 月份在JS里面是从0开始的
        str=str.replace(/MM/,this.getMonth()>=9?(this.getMonth()+1).toString():'0' + (this.getMonth()+1));
        str=str.replace(/M/g,this.getMonth());

        str=str.replace(/w|W/g,Week[this.getDay()]);

        str=str.replace(/dd|DD/,this.getDate()>9?this.getDate().toString():'0' + this.getDate());
        str=str.replace(/d|D/g,this.getDate());

        str=str.replace(/hh|HH/,this.getHours()>9?this.getHours().toString():'0' + this.getHours());
        str=str.replace(/h|H/g,this.getHours());
        str=str.replace(/mm/,this.getMinutes()>9?this.getMinutes().toString():'0' + this.getMinutes());
        str=str.replace(/m/g,this.getMinutes());

        str=str.replace(/ss|SS/,this.getSeconds()>9?this.getSeconds().toString():'0' + this.getSeconds());
        str=str.replace(/s|S/g,this.getSeconds());

        return str;
    };
})();

var Tools = {
    /**
     * 菜单key制
     */
    MENU_KEY_IN_COOKIE: 'MENU_KEY_IN_COOKIE',
    /**
     * 设置cookie值
     * @param name cookie name
     * @param value cookie value
     * @param hours 时间(小时)
     */
    setCookie: function (name, value, hours) {
        var d = new Date();
        var offset = 8;
        var utc = d.getTime() + (d.getTimezoneOffset() * 60000);
        var nd = utc + (3600000 * offset);
        var exp = new Date(nd);
        exp.setTime(exp.getTime() + hours * 60 * 60 * 1000);
        document.cookie = name + "=" + escape(value) + ";path=/;expires=" + exp.toGMTString();
    },

    /**
     * 获取cookie值
     * @param name cookie名称
     * @returns {null} cookie值
     */
    getCookie: function (name) {
        var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
        if (arr != null)
            return unescape(arr[2]);
        return null;
    },

    /**
     * 设置menu到cookie
     * @param menu 菜单项
     */
    setMenu: function (menu) {
        this.setCookie(this.MENU_KEY_IN_COOKIE, menu, 24 * 7);
    },

    /**
     * 获取menu
     */
    getMenu: function () {
        return this.getCookie(this.MENU_KEY_IN_COOKIE);
    },

    // 图片加载失败调用方法
    onLoadImgErrorCallback: function (element, targetSrc) {
        element.src = contextPath + targetSrc;
    },

    /**
     * 手机号是否合法
     * @param mobileNo 手机号码
     * @returns {boolean} 合法返回true，反之返回false
     */
    isMobileNo: function (mobileNo) {
        var reg = new RegExp('^1\\d{10}$');
        return reg.test(mobileNo);
    },

    /**
     * 校验是否数字
     *
     * @param numb
     */
    isNumber: function (numb) {
        var reg = new RegExp('^[0-9]*$');
        return reg.test(numb);
    },

    account: function (numb) {
        var reg = new RegExp('^[A-Z|a-z|0-9|_]+$');
        return reg.test(numb);
    },

    /**
     * 校验是否数字（两位小数）
     *
     * @param numb
     */
    isNumberAndDoubleDigit: function (numb) {
        var reg = new RegExp('^([0-9]*)+(.[0-9]{1,2})?$');
        return reg.test(numb);
    },

    /**
     * 校验是否包含非法字符
     *
     * @param numb
     */
    unlawfulnessChars: function (numb) {
        var reg = new RegExp('^[0-9|A-Z|a-z|\u4E00-\u9FA5|-]+$');
        return reg.test(numb);
    },

    /**
     * 地址校验
     *
     * @param numb
     */
    isAddress: function (numb) {
        var reg = new RegExp('^[\u4E00-\u9FA5A-Za-z0-9_]+$');
        return reg.test(numb);
    },

    /**
     * 包含数字字母
     *
     * @param numb
     */
    isNumberLetter: function (numb) {
        var reg = new RegExp('^[0-9|a-zA-Z]+$');
        return reg.test(numb);
    },

    /**
     * 燃油名称
     *
     * @param numb
     */
    isOilName: function (numb) {
        var reg = new RegExp('^[\u4E00-\u9FA5A-Za-z0-9#.]+$');
        return reg.test(numb);
    },

    // 常量值
    constant: {
        truckTicket: 4010,
        truckPic: 4020,
        host: {
            adminHost: "adminHost",
            kylebussHost: "kylebussHost",
            stanHost: "stanHost",
            stanbussHost: "stanbussHost",
            stanbusscityHost: "stanbusscityHost",
            stancityHost: "stancityHost",
            tmsdriverHost: "tmsdriverHost",
            subsupplierHost: "subsupplierHost"
        }

    },
    getOrderStatus: {
        getPublished: function () {
            return 10;
        },
        getConfirmed: function () {
            return 30;
        },
        getWaitextracted: function () {
            return 40;
        },
        getExtracted: function () {
            return 50;
        },
        getAlreadystart: function () {
            return 60;
        },
        getIntransit: function () {
            return 70;
        },
        getCompleted: function () {
            return 80;
        },
        getDone: function () {
            return 90;
        },
        getCanceled: function () {
            return 100;
        }
    },
    getWayBillType: {
        // 接单
        getBidself: function () {
            return 10;
        },
        // 派单
        getAssing: function () {
            return 20;
        }
    },
    getWayBillStatus: {
        getWaitbid: function () {
            return 10;
        },
        getAlreadybid: function () {
            return 20;
        },
        getWaitextracted: function () {
            return 30;
        },
        getExtracted: function () {
            return 40;
        },
        getWaitstart: function () {
            return 50;
        },
        getWaitcomplete: function () {
            return 60;
        },
        getCompleted: function () {
            return 80;
        },
        getDone: function () {
            return 90;
        },
        getCanceled: function () {
            return 100;
        }
    },
    getWaybillStatusText: function (status) {
        if (status == Tools.getWayBillStatus.getWaitbid()) {
            return '待接单';
        } else if (status == Tools.getWayBillStatus.getAlreadybid()) {
            return '已接单';
        } else if (status == Tools.getWayBillStatus.getWaitextracted()) {
            return '待提车';
        } else if (status == Tools.getWayBillStatus.getExtracted()) {
            return '已提车';
        } else if (status == Tools.getWayBillStatus.getWaitstart()) {
            return '待发车';
        } else if (status == Tools.getWayBillStatus.getWaitcomplete()) {
            return '待交车';
        } else if (status == Tools.getWayBillStatus.getCompleted()) {
            return '已交车';
        } else if (status == Tools.getWayBillStatus.getDone()) {
            return '已完成';
        } else if (status == Tools.getWayBillStatus.getCanceled()) {
            return '已取消';
        }
    },
    getDWaybillStatus: {
        getSave: function () {
            return 0;
        },
        getDeparture: function () {
            return 5;
        },
        getIntransit: function () {
            return 10;
        },
        getDealCar: function () {
            return 20;
        },
        getCompleted: function () {
            return 30;
        },
        getExceptionConfirm: function () {
            return 40;
        },
        getCancel: function () {
            return 90;
        },
        getFailure: function () {
            return 100;
        }
    },
    getDWaybillStatusText: function (status) {
        if (status == Tools.getDWaybillStatus.getSave()) {
            return '未安排订单';
        } else if (status == Tools.getDWaybillStatus.getDeparture()) {
            return '待发车';
        } else if (status == Tools.getDWaybillStatus.getIntransit()) {
            return '在途';
        } else if (status == Tools.getDWaybillStatus.getDealCar()) {
            return '已交车';
        } else if (status == Tools.getDWaybillStatus.getCompleted()) {
            return '已完成';
        } else if (status == Tools.getDWaybillStatus.getExceptionConfirm()) {
            return '未回单';
        } else if (status == Tools.getDWaybillStatus.getCancel()) {
            return '取消';
        } else if (status == Tools.getDWaybillStatus.getFailure()) {
            return '派单失败';
        }
    },
    getDeliveryCheckStatus: {
        getWaitbid: function () {
            return 0;
        },
        getPassid: function () {
            return 1;
        }
    },
    getDeliveryCheckStatusText: function (status) {
        if (status == Tools.getDeliveryCheckStatus.getWaitbid()) {
            return '待审核';
        } else if (status == Tools.getDeliveryCheckStatus.getPassid()) {
            return '已审核';
        }
    },
    getSelfStatus: {
        isSelf: function () {
            return 0;
        },
        isNotSelf: function () {
            return 1;
        }
    },
    getIsSelfText: function (status) {
        if (status == Tools.getSelfStatus.isSelf()) {
            return '异常';
        } else if (status == Tools.getSelfStatus.isNotSelf()) {
            return '通过';
        }
    },
    getLockStatus: {
        getlockid: function () {
            return 0;
        },
        getUnlockid: function () {
            return 1;
        }
    },
    getLockStatusText: function (status) {
        if (status == Tools.getLockStatus.getlockid()) {
            return '解锁';
        } else if (status == Tools.getLockStatus.getUnlockid()) {
            return '锁定';
        }
    },
    getSUserBindDeviceStatus: {
        getBind: function () {
            return true;
        },
        getUnBind: function () {
            return false;
        }
    },
    getSUserBindDeviceStatusText: function (status) {
        if (status == Tools.getSUserBindDeviceStatus.getBind()) {
            return '绑定';
        } else if (status == Tools.getSUserBindDeviceStatus.getUnBind()) {
            return '未绑定';
        }
    },
    getDWaybillDamageStatus: {
        getStayAudit: function () {
            return 0;
        },
        getAuditing: function () {
            return 1;
        },
        getPassed: function () {
            return 2;
        },
        getNotPass: function () {
            return 3;
        }
    },
    getDWaybillDamageStatusText: function (status) {
        if (status == Tools.getDWaybillDamageStatus.getStayAudit()) {
            return '待审核';
        } else if (status == Tools.getDWaybillDamageStatus.getAuditing()) {
            return '审核中';
        } else if (status == Tools.getDWaybillDamageStatus.getPassed()) {
            return '已通过审核';
        } else if (status == Tools.getDWaybillDamageStatus.getNotPass()) {
            return '未通过审核';
        }
    },
    getDAccidentStatus: {
        getStayAudit: function () {
            return 0;
        },
        getAuditing: function () {
            return 1;
        },
        getPassed: function () {
            return 2;
        },
        getNotPass: function () {
            return 3;
        }
    },
    getDAccidentStatusText: function (status) {
        if (status == Tools.getDAccidentStatus.getStayAudit()) {
            return '待审核';
        } else if (status == Tools.getDAccidentStatus.getAuditing()) {
            return '审核中';
        } else if (status == Tools.getDAccidentStatus.getPassed()) {
            return '已通过审核';
        } else if (status == Tools.getDAccidentStatus.getNotPass()) {
            return '未通过审核';
        }
    },
    getWayBillPayStatus: {
        getUnpaid: function () {
            return 10;
        },
        getWaitPayment: function () {
            return 20;
        },
        getAlreadyPaid: function () {
            return 30
        }
    },
    getWaybillPayStatusText: function (payStatus) {
        if (payStatus == Tools.getWayBillPayStatus.getUnpaid()) {
            return '未支付';
        } else if (payStatus == Tools.getWayBillPayStatus.getWaitPayment()) {
            return '待支付';
        } else if (payStatus == Tools.getWayBillPayStatus.getAlreadyPaid()) {
            return '已支付';
        }
    },
    getDeliveryAuditCode: {
        getPassCode: function () {
            return 10;
        },
        getApproveQueueCode: function () {
            return 20;
        },
        getForbiddenQueueCode: function () {
            return 30;
        }
    },
    getDeliveryAuditName: function (auditCode) {
        if (auditCode == Tools.getDeliveryAuditCode.getPassCode()) {
            return '通过';
        } else if (auditCode == Tools.getDeliveryAuditCode.getApproveQueueCode()) {
            return '交车异常但可排队';
        } else if (auditCode == Tools.getDeliveryAuditCode.getForbiddenQueueCode()) {
            return '交车异常不可排队';
        }
    },
    getDeliveryIssueDisposalTypeCode: {
        getPassCode: function () {
            return 10;
        },
        getForbiddenQueueCode: function () {
            return 20;
        }
    },
    getDeliveryIssueDisposalTypeName: function (disposalTypeCode) {
        if (disposalTypeCode == Tools.getDeliveryIssueDisposalTypeCode.getPassCode()) {
            return '警告';
        } else if (disposalTypeCode == Tools.getDeliveryIssueDisposalTypeCode.getForbiddenQueueCode()) {
            return '不可排队';
        }
    },
    getDeliveryErrorText: function (errorCode) {
        if (errorCode == 10) {
            return '司机本人照片尚未采集';
        } else if (errorCode == 20) {
            return '交车照片模糊';
        } else if (errorCode == 30) {
            return '单据照片模糊';
        } else if (errorCode == 40) {
            return '合影照片模糊';
        }
    },
    getAttachType: {
        getReceipt: function () {
            return 10;
        },
        getSend: function () {
            return 20;
        },
        getDeliver: function () {
            return 30;
        },
        getReceive: function () {
            return 40;
        }
    },
    getAttachTypeEnum: {
        getReceiptBill: function () {
            return 1010; // 提车单据
        },
        getReceiptPhoto: function () {
            return 1020; // 提车照片
        },
        getDeliverBill: function () {
            return 3010; // 交车单据
        },
        getDeliverPhoto: function () {
            return 3020; // 交车照片
        },
        getUnionPhoto: function () {
            return 3030; // 合影照片
        }
    },
    getContactType: {
        getDriver: function () {
            return 10;
        },
        getDepartPerson: function () {
            return 20;
        },
        getReceiptPerson: function () {
            return 30;
        }
    },
    getVehicleClass: function (code) {
        if (code == 'S') {
            return 1;
        } else if (code == 'M') {
            return 2;
        } else if (code == 'L') {
            return 3;
        } else if (code == 'EX') {
            return 4;
        }
    },
    getServiceOrderStatusText: function (code) {
        if (code == 45) {
            return '待调度';
        } else if (code == 50) {
            return '待提车';
        } else if (code == 60) {
            return '已提车';
        } else if (code == 70) {
            return '已发车';
        } else if (code == 80) {
            return '已交车';
        } else if (code == 90) {
            return '已完成';
        } else if (code == 100) {
            return '已取消';
        }
    },
    getDUserOilCardStatus: {
        getNormal: function () {
            return '10';
        },
        getLossOf: function () {
            return '20';
        },
        getQuitCard: function () {
            return '30';
        },
        getNotBind: function () {
            return '40';
        }
    },
    getDUserOilCardStatusText: function (status) {
        if (status == Tools.getDUserOilCardStatus.getNormal()) {
            return "正常";
        } else if (status == Tools.getDUserOilCardStatus.getLossOf()) {
            return "挂失";
        } else if (status == Tools.getDUserOilCardStatus.getQuitCard()) {
            return "退卡";
        } else if (status == Tools.getDUserOilCardStatus.getNotBind()) {
            return "未绑";
        }
    },
    socket: {
        init: function () {
            var that = this;
            var socket;
            if (!window.WebSocket) window.WebSocket = window.MozWebSocket;
            // Javascript Websocket Client
            if (window.WebSocket) {
                socket = new WebSocket("ws://" + host + "/websocket");
                socket.onmessage = function (event) {
                    console.log("Web Socket message: " + event.data);
                };
                socket.onopen = function (event) {
                    that.sendMessage(JSON.stringify({"directive": "connect", "userId": user.id}));
                    console.log("-------open-------");
                };
                socket.onclose = function (event) {
                    console.log("-------closed-------");
                };
                return;
            }
            console.log("Your browser does not support Web Socket.");
        },
        sendMessage: function (message) {
            if (!window.WebSocket) return;
            if (socket.readyState == WebSocket.OPEN) {
                socket.send(message);
                return;
            }
            console.log("The socket is not open.");
        }
    },
    layer: {
        alert: function (content, title, callback) {
            var index = layer.alert(content, {
                skin: 'layer-btn-class',
                closeBtn: 0,
                title: title
            }, function () {
                layer.close(index);
                if (callback) callback();
            });
        },
        confirm: function (content, title, okbtn, cancelbtn, okCallback, cancelCallback) {
            var index = layer.confirm(content, {
                title: title,
                skin: 'layer-btn-class',
                btn: [okbtn, cancelbtn]
            }, function () {
                layer.close(index);
                if (okCallback) okCallback();
            }, function () {
                layer.close(index);
                if (cancelCallback) cancelCallback();
            });
        },
        open: function (option) {
            var index = 0;
            var _option = _.extend({
                type: 1,
                title: '页面层',
                shadeClose: true,
                shade: 0.3,
                maxmin: false,
                area: ['60%', '80%'],
                content: '慧运车欢迎你',
                cancel: function () {
                    layer.close(index);
                    if (option.callback) option.callback();
                }
            }, option);
            this.open.index = index = layer.open(_option);
        }
    }
}